package net.fei.scan.quick.db

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.util.Log
import net.fei.scan.quick.db.DatabaseHelper.Companion.COLUMN_CURRENT_TIME
import net.fei.scan.quick.db.DatabaseHelper.Companion.STATUS
import net.fei.scan.quick.entity.History
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class DbUtils(private val context: Context) {

    private val dbHelper = DatabaseHelper(context)

    fun insertData(title: String, content: String,  type: String, image: Int,status:Int) {
        val db = dbHelper.writableDatabase
        val values = ContentValues().apply {
            put(DatabaseHelper.COLUMN_TITLE, title)
            put(DatabaseHelper.COLUMN_CONTENT, content)
            put(DatabaseHelper.COLUMN_CURRENT_TIME, getCurrentTime())
            put(DatabaseHelper.COLUMN_TYPE, type)
            put(DatabaseHelper.IMAGE, image)
            put(DatabaseHelper.STATUS, status)
        }

     db.insert(DatabaseHelper.TABLE_NAME, null, values)
        db.close()
    }

    fun deleteData(id: Long) {
        val db = dbHelper.writableDatabase
        db.delete(DatabaseHelper.TABLE_NAME, "${DatabaseHelper.COLUMN_ID}=?", arrayOf(id.toString()))
        db.close()
    }

    @SuppressLint("Range")
    fun getAllData(status:Int): List<History> {
        val dataList = mutableListOf<History>()
        val db = dbHelper.readableDatabase

        val query = "SELECT * FROM ${DatabaseHelper.TABLE_NAME} WHERE $STATUS = ? ORDER BY $COLUMN_CURRENT_TIME DESC"
        val cursor: Cursor = db.rawQuery(query, arrayOf(status.toString()))

        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getLong(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID))
                val title = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TITLE))
                val content = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_CONTENT))
                val currentTime = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_CURRENT_TIME))
                val type = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TYPE))
                val image = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.IMAGE))
                val history = History(id, title, content, currentTime, type, image)

                dataList.add(history)
            } while (cursor.moveToNext())
        }

        cursor.close()
        db.close()

        return dataList
    }
    private fun getCurrentTime(): String {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"))
    }
}
